package com.bkgy.modular.tbrealtimevariable.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baosight.hdsdk.domain.data.HDDataConnection;
import com.bkgy.modular.tbrealtimevariable.dao.TbRealTimeVariableDao;
import com.bkgy.modular.tbrealtimevariable.entity.JTbRealTimeVariable;
import com.bkgy.modular.tbrealtimevariable.entity.TbRealTimeVariable;
import com.bkgy.modular.tbrealtimevariable.service.TbRealTimeVariableService;
import com.bkgy.sys.common.entity.ResultData;
import com.bkgy.util.SDKUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 仿真数据接口具体实现类
 *
 * @author 生成器生成
 * @date 2022-10-17 09:29:12
 */
@Service
public class TbRealTimeVariableServiceImpl extends ServiceImpl<TbRealTimeVariableDao, TbRealTimeVariable> implements TbRealTimeVariableService {

    HDDataConnection connect = new HDDataConnection();
    @Resource
    private TbRealTimeVariableDao tbRealTimeVariableDao;
    @Resource
    private SDKUtils sdkUtils;

    /**
     * 添加记录
     *
     * @param data   json字符串
     * @param userId 用户id
     * @param sname  用户姓名
     */
    public ResultData insertDataTbRealTimeVariable(String data, Long userId, String sname) {
        try {
            JTbRealTimeVariable jTbRealTimeVariable = JSON.parseObject(data, JTbRealTimeVariable.class);
            TbRealTimeVariable tbRealTimeVariable = jTbRealTimeVariable.getTbRealTimeVariable();
            tbRealTimeVariableDao.insert(tbRealTimeVariable);
            return ResultData.ResultDataSuccessSelf("添加数据成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("添加失败，错误信息为" + e.getMessage(), null);
        }
    }

    /**
     * 根据主键删除对象
     *
     * @param indocno 对象主键
     */
    public ResultData deleteOne(Long indocno) {
        try {
            tbRealTimeVariableDao.deleteById(indocno);
            return ResultData.ResultDataSuccessSelf("删除数据成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("删除失败,失败信息为" + e.getMessage(), null);
        }
    }

    /**
     * 根据主键字符串删除多个对象
     *
     * @param str_indocno 对象主键字符串
     */
    public ResultData deleteMany(String str_indocno) {
        try {
            if (!ObjectUtils.isEmpty(str_indocno)) {
                List<String> idlist = Arrays.asList(str_indocno.split(","));
                if (!ObjectUtils.isEmpty(idlist) && idlist.size() != 0) {
                    List<Integer> ids = idlist.stream().map(Integer::getInteger).collect(Collectors.toList());
                    tbRealTimeVariableDao.deleteBatchIds(ids);
                }
                return ResultData.ResultDataSuccessSelf("删除数据数据成功", null);
            } else {
                return ResultData.ResultDataFaultSelf("删除失败,主键集合为空", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("删除失败,失败信息为" + e.getMessage(), null);
        }
    }

    /**
     * 修改记录
     *
     * @param userId 用户id
     * @param sname  用户姓名
     * @param data   数据
     */
    public ResultData updateDataTbRealTimeVariable(String data, Long userId, String sname) {
        try {
            JTbRealTimeVariable jTbRealTimeVariable = JSON.parseObject(data, JTbRealTimeVariable.class);
            TbRealTimeVariable tbRealTimeVariable = jTbRealTimeVariable.getTbRealTimeVariable();
            tbRealTimeVariableDao.updateById(tbRealTimeVariable);
            return ResultData.ResultDataSuccessSelf("修改成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("修改失败,失败信息为" + e.getMessage(), null);
        }
    }

    /**
     * 分页查看记录
     *
     * @param data 数据
     */
    public ResultData findDataTbRealTimeVariableByPage(String data) {
        try {
            JTbRealTimeVariable jTbRealTimeVariable = JSON.parseObject(data, JTbRealTimeVariable.class);
            JSONObject jsonObject = null;
            Integer pageIndex = jTbRealTimeVariable.getPageIndex();
            Integer pageSize = jTbRealTimeVariable.getPageSize();

            if (null == pageIndex || null == pageSize) {
                return ResultData.ResultDataFaultSelf("分页参数没有传", null);
            }

            if (null != jTbRealTimeVariable.getCondition()) {
                jsonObject = JSON.parseObject(jTbRealTimeVariable.getCondition().toString());
            }

            LambdaQueryWrapper<TbRealTimeVariable> wrapper = new LambdaQueryWrapper<>();

            String l1_variable_name = null;
            if (!ObjectUtils.isEmpty(jsonObject.getString("l1_variable_name"))) {
                l1_variable_name = jsonObject.getString("l1_variable_name");
                String[] strList = l1_variable_name.split(",");
                StringBuilder applysql = new StringBuilder();
                String sql = "";
                if (strList.length != 0) {
                    for (int i = 0; i < strList.length; i++) {
                        if (i == 0) {
                            sql = "l1_variable_name like '%" + strList[i] + "%'";
                        } else {
                            sql = "or l1_variable_name like '%" + strList[i] + "%'";
                        }
                        applysql.append(sql);
                    }
                }
                wrapper.apply(applysql.toString());
            }

            Page<TbRealTimeVariable> page = new Page<>(pageIndex, pageSize);
            Page<TbRealTimeVariable> resultPage = tbRealTimeVariableDao.selectPage(page, wrapper);
            List<TbRealTimeVariable> list = resultPage.getRecords();
            Integer count = (int) resultPage.getSize();
            return ResultData.ResultDataSuccess(list, count);

        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("查询失败,失败信息为" + e.getMessage(), null);
        }
    }

    /**
     * 根据主键查询单条记录
     *
     * @param data 数据
     */
    public ResultData findDataTbRealTimeVariableByIndocno(String data) {
        try {
            JTbRealTimeVariable jTbRealTimeVariable = JSON.parseObject(data, JTbRealTimeVariable.class);
            TbRealTimeVariable tbRealTimeVariable = tbRealTimeVariableDao.selectById(jTbRealTimeVariable.getIndocno());
            return ResultData.ResultDataSuccess(tbRealTimeVariable);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("查询失败,失败信息为" + e.getMessage(), null);
        }
    }

    /**
     * 自动任务：获取真值与当前时间，并存入表中
     */
    //@Scheduled(cron = "${updatetimes}")
    public void getRealValue() {
        // log.error("TbRealTimeVariableServiceImpl+getRealValue");
        List<TbRealTimeVariable> list = tbRealTimeVariableDao.selectList(null);
        if (list.size() != 0) {
            //断链重连
            while (!connect.isConnected()) {
                connect = sdkUtils.getConnect();
            }
            //在已链接的情况下查询值
            if (connect.isConnected()) {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS");
                for (TbRealTimeVariable entity : list) {
                    try {
                        //查询当前值
                        String value = sdkUtils.findDataOneById2(entity.getL1_variable_name(), sdkUtils.findTagId(entity.getL1_variable_name(), connect.getTagManager()), connect.getDataProvider());
                        //实体类赋值
                        entity.setReal_value(value);
                        entity.setUpdate_time(LocalDateTime.now().format(formatter));
                        //根据名称更新数据
                        LambdaQueryWrapper<TbRealTimeVariable> wrapper = new LambdaQueryWrapper<>();
                        wrapper.eq(TbRealTimeVariable::getL1_variable_name, entity.getL1_variable_name());
                        tbRealTimeVariableDao.update(entity, wrapper);
                    } catch (Exception e) {
                        log.error("TbRealTimeVariableServiceImpl+getRealValue,tag无数据：" + entity.getL1_variable_name());
                    }
                }
            }
        }
    }

    /**
     * 自动任务：每十分钟检查一次连接是否正常
     */
   // @Scheduled(cron = "${sdktime}")
    public void connect() {
        log.error("TbRealTimeVariableServiceImpl+connect");
        while (!connect.isConnected()) {
            connect = sdkUtils.getConnect();
        }
    }
}